package leetcode.backtrace;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author 26233
 * @Create 2021-03-31 10:50:15
 */
/*
给定两个整数 n 和 k，返回 1 ... n 中所有可能的 k 个数的组合。

示例:

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/combinations
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class LeetCode77_Combine {
    public List<List<Integer>> combine(int n, int k) {

        List<List<Integer>> result = new ArrayList<>();
        List<Integer> tempResult = new ArrayList<>();
        int[] visited = new int[n + 1];

        combine(result, tempResult, visited, n, k, 0);

        return result;
    }

    public void combine(List<List<Integer>> result, List<Integer> tempResult,  int[] visited, int n, int k, int index){
        if (tempResult.size() == k){
            List<Integer> r = new ArrayList<>(tempResult);
            result.add(r);
            return;
        }
        for (int i = 1; i <= n; i++) {
            if(visited[i] == 0 && i >= index){
                tempResult.add(i);
                visited[i] = 1;
                combine(result, tempResult, visited, n, k, i);
                visited[i] = 0;
                tempResult.remove(new Integer(i));
            }
        }
    }

    //////////////////////////
    public List<List<Integer>> combine2(int n, int k) {

        List<List<Integer>> result = new ArrayList<>();
        List<Integer> tempResult = new ArrayList<>();
        combine(result, tempResult, n, k, 1);

        return result;
    }

    public void combine(List<List<Integer>> result, List<Integer> tempResult, int n, int k, int index){
        if (tempResult.size() == k){
            List<Integer> r = new ArrayList<>(tempResult);
            result.add(r);
            return;
        }
        //for (int i = index; i <= n; i++) {
        //剪枝优化：n = 7, k = 4，从 55 开始搜索就已经没有意义了
        for (int i = index; i <= n - (k - tempResult.size()) + 1; i++) {
                tempResult.add(i);
                combine(result, tempResult, n, k, i + 1);
                tempResult.remove(new Integer(i));
        }
    }

    public static void main(String[] args) {
        int n = 4, k = 2;
        // List<List<Integer>> result = new LeetCode77_Combine().combine(n, k);
        List<List<Integer>> result = new LeetCode77_Combine().combine2(n, k);

        System.out.println("result = " + result);
    }
}
